const app = getApp()
const { get } = require('../../utils/request')

Page({
  data: {
    hasLogin: false,
    userStats: null,
    recommendRecipes: {
      breakfast: [],
      lunch: [],
      dinner: []
    }
  },

  onLoad() {
    this.setData({
      hasLogin: app.globalData.hasLogin
    })
    
    if (app.globalData.hasLogin) {
      this.getRecommendRecipes()
    }
  },

  onShow() {
    // 检查登录状态是否发生变化
    if (this.data.hasLogin !== app.globalData.hasLogin) {
      this.setData({
        hasLogin: app.globalData.hasLogin
      })
      if (app.globalData.hasLogin) {
        this.getRecommendRecipes()
      }
    }
  },

  async getRecommendRecipes() {
    try {
      wx.showLoading({
        title: '加载中...'
      })

      const result = await get('/recipes/recommend')
      
      this.setData({
        userStats: result.userStats,
        recommendRecipes: result.recipes
      })

    } catch (error) {
      console.error('获取推荐食谱失败:', error)
      wx.showToast({
        title: '获取推荐失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  viewRecipeDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/recipe/detail?id=${id}`
    })
  },

  viewMore(e) {
    const type = e.currentTarget.dataset.type
    wx.switchTab({
      url: `/pages/recipe/list?category=${type}`
    })
  },

  navigateToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  onPullDownRefresh() {
    if (app.globalData.hasLogin) {
      this.getRecommendRecipes().then(() => {
        wx.stopPullDownRefresh()
      })
    } else {
      wx.stopPullDownRefresh()
    }
  }
}) 